package com.cd2cd.code_template.configuration;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;

import com.cd2cd.code_template.configuration.constants.ServiceCode;
import com.cd2cd.code_template.vo.BaseRes;

/**
 * controller 统一验证 
 */
@Slf4j
@Aspect
@Component
public class ControllerValidatorAspect {

	@Around("execution(* com.cd2cd.code_template..*.controller..*.*(..)) && args(..,bindingResult)")
	public Object doAround(ProceedingJoinPoint pjp, BindingResult bindingResult) throws Throwable {
		if (bindingResult.hasErrors()) {
			BaseRes<String> res = new BaseRes<>();
			
			String errmsg = "";
			for(ObjectError oe: bindingResult.getAllErrors()) {
				DefaultMessageSourceResolvable dmsr = (DefaultMessageSourceResolvable)oe.getArguments()[0];
				errmsg += dmsr.getCode()+ "-"+ oe.getCode()+",";
			}
			
			res.setMsg(errmsg);
			res.setServiceCode(ServiceCode.INVALID_PARAMS);


			Class cName = pjp.getTarget().getClass();
			String fName = pjp.getSignature().getName();

			log.info("{}-{}, invalidate={}", cName, fName, errmsg);
			return res;
		} else {
			return pjp.proceed();
		}
	}
}